<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { Page } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { formatDate as formatDateUtil } from '@vben/utils';

import {
  Button,
  Col,
  DatePicker,
  Input,
  message,
  Modal,
  Pagination,
  Row,
  Select,
  SelectOption,
  Spin,
  Tag,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import {
  cancelBooking as cancelBookingApi,
  getMyBookings,
  takeQueueTicket as takeQueueTicketApi,
} from '#/api/booking';

const router = useRouter();

const loading = ref(false);
const bookings = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const dateRange = ref<any>(undefined);

const queryParams = reactive({
  status: '',
  serviceName: '',
  startDate: '',
  endDate: '',
});

const loadBookings = async () => {
  try {
    loading.value = true;
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...queryParams,
    };

    const result = await getMyBookings(params);
    console.log('预约数据:', result);

    // 确保数据格式正确
    bookings.value = result.list || [];
    total.value = result.total || 0;

    // 验证每个预约记录的日期字段
    bookings.value.forEach((booking: any, index: number) => {
      console.log(`预约 ${index + 1} 的日期字段:`, {
        bookingDate: booking.bookingDate,
        type: typeof booking.bookingDate,
        isValid: dayjs(booking.bookingDate).isValid(),
      });

      if (booking.bookingDate) {
        // 确保日期是字符串格式
        if (typeof booking.bookingDate !== 'string') {
          console.warn('预约日期格式异常:', booking.bookingDate);
          booking.bookingDate = String(booking.bookingDate);
        }

        // 验证日期是否有效
        if (!dayjs(booking.bookingDate).isValid()) {
          console.warn('无效的预约日期:', booking.bookingDate);
          booking.bookingDate = null;
        }
      }
    });
  } catch (error) {
    console.error('加载预约记录失败:', error);
    message.error('加载预约记录失败');
    bookings.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

const resetFilters = () => {
  queryParams.status = '';
  queryParams.serviceName = '';
  queryParams.startDate = '';
  queryParams.endDate = '';
  dateRange.value = undefined;
  currentPage.value = 1;
  loadBookings();
};

const handleDateChange = (dates: any) => {
  if (dates && dates.length === 2) {
    queryParams.startDate = dayjs(dates[0]).format('YYYY-MM-DD');
    queryParams.endDate = dayjs(dates[1]).format('YYYY-MM-DD');
  } else {
    queryParams.startDate = '';
    queryParams.endDate = '';
  }
  currentPage.value = 1;
  loadBookings();
};

const handlePageChange = (page: number) => {
  currentPage.value = page;
  loadBookings();
};

const handlePageSizeChange = (current: number, size: number) => {
  currentPage.value = 1;
  pageSize.value = size;
  loadBookings();
};

const takeQueueTicket = async (booking: any) => {
  try {
    const result = await takeQueueTicketApi(booking.id);
    message.success('取号成功！');
    loadBookings();
  } catch (error) {
    console.error('取号失败:', error);
    message.error('取号失败，请重试');
  }
};

const cancelBooking = (booking: any) => {
  Modal.confirm({
    title: '确认取消预约',
    content: `确定要取消预约"${booking.serviceName}"吗？`,
    onOk: async () => {
      try {
        await cancelBookingApi(booking.id);
        message.success('预约已取消');
        loadBookings();
      } catch (error) {
        console.error('取消预约失败:', error);
        message.error('取消预约失败');
      }
    },
  });
};

const viewQueueStatus = (booking: any) => {
  router.push('/booking/queue');
};

const viewBookingDetail = (booking: any) => {
  // 可以打开详情弹窗或跳转到详情页面
  console.log('查看预约详情:', booking);
};

const goToBooking = () => {
  router.push('/booking');
};

const formatDate = (date: any) => {
  if (!date) return '--';
  try {
    return formatDateUtil(date);
  } catch (error) {
    console.error('日期格式化错误:', error, date);
    return '--';
  }
};

const getStatusClass = (status: string) => {
  return `status-${status.toLowerCase()}`;
};

const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    PENDING: 'orange',
    CONFIRMED: 'blue',
    IN_PROGRESS: 'green',
    COMPLETED: 'default',
    CANCELLED: 'red',
  };
  return colorMap[status] || 'default';
};

const getStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    PENDING: '待确认',
    CONFIRMED: '已确认',
    IN_PROGRESS: '进行中',
    COMPLETED: '已完成',
    CANCELLED: '已取消',
  };
  return textMap[status] || '未知状态';
};

onMounted(() => {
  loadBookings();
});
</script>

<template>
  <div class="my-bookings-page">
    <Page title="我的预约" content="查看和管理您的预约记录">
      <div class="bookings-container">
        <!-- 筛选条件 -->
        <div class="filters-section">
          <Row :gutter="16">
            <Col :span="6">
              <Select
                v-model:value="queryParams.status"
                placeholder="预约状态"
                allow-clear
                @change="loadBookings"
              >
                <SelectOption value="">全部状态</SelectOption>
                <SelectOption value="PENDING">待确认</SelectOption>
                <SelectOption value="CONFIRMED">已确认</SelectOption>
                <SelectOption value="IN_PROGRESS">进行中</SelectOption>
                <SelectOption value="COMPLETED">已完成</SelectOption>
                <SelectOption value="CANCELLED">已取消</SelectOption>
              </Select>
            </Col>
            <Col :span="6">
              <DatePicker.RangePicker
                v-model:value="dateRange"
                :placeholder="['开始日期', '结束日期']"
                @change="handleDateChange"
              />
            </Col>
            <Col :span="6">
              <Input
                v-model:value="queryParams.serviceName"
                placeholder="服务项目"
                @press-enter="loadBookings"
              />
            </Col>
            <Col :span="6">
              <Button type="primary" @click="loadBookings" :loading="loading">
                <IconifyIcon icon="mdi:search" />
                搜索
              </Button>
              <Button @click="resetFilters" style="margin-left: 8px">
                重置
              </Button>
            </Col>
          </Row>
        </div>

        <!-- 预约列表 -->
        <div class="bookings-list">
          <div v-if="loading" class="loading-state">
            <Spin size="large" />
            <p>加载中...</p>
          </div>

          <div v-else-if="bookings.length === 0" class="empty-state">
            <IconifyIcon icon="mdi:calendar-blank" class="empty-icon" />
            <h3>暂无预约记录</h3>
            <p>您还没有预约任何服务</p>
            <Button type="primary" @click="goToBooking">
              <IconifyIcon icon="mdi:calendar-plus" />
              立即预约
            </Button>
          </div>

          <div v-else class="bookings-grid">
            <div
              v-for="booking in bookings"
              :key="booking.id"
              class="booking-card"
              :class="getStatusClass(booking.status)"
            >
              <div class="booking-header">
                <div class="booking-info">
                  <h3 class="service-name">{{ booking.serviceName }}</h3>
                  <p class="booking-time">
                    {{ formatDate(booking.bookingDate) }} {{ booking.timeSlot }}
                  </p>
                </div>
                <div class="booking-status">
                  <Tag :color="getStatusColor(booking.status)">
                    {{ getStatusText(booking.status) }}
                  </Tag>
                </div>
              </div>

              <div class="booking-details">
                <div class="detail-row">
                  <span class="label">预约号：</span>
                  <span class="value">{{ booking.bookingNo }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">客户姓名：</span>
                  <span class="value">{{ booking.customerName }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">手机号：</span>
                  <span class="value">{{ booking.phoneNumber }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">取号：</span>
                  <span class="value queue-number">{{
                    booking.queueTicket || '未取号'
                  }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">排队位置：</span>
                  <span class="value">{{
                    booking.queuePosition || '未排队'
                  }}</span>
                </div>
                <div class="detail-row">
                  <span class="label">预计等待：</span>
                  <span class="value">{{
                    booking.estimatedWaitTime || '--'
                  }}</span>
                </div>
                <div v-if="booking.remarks" class="detail-row">
                  <span class="label">备注：</span>
                  <span class="value remarks">{{ booking.remarks }}</span>
                </div>
              </div>

              <div class="booking-actions">
                <Button
                  v-if="booking.status === 'CONFIRMED' && !booking.queueTicket"
                  type="primary"
                  size="small"
                  @click="takeQueueTicket(booking)"
                >
                  取号排队
                </Button>
                <Button
                  v-if="booking.status === 'PENDING'"
                  type="default"
                  size="small"
                  @click="cancelBooking(booking)"
                >
                  取消预约
                </Button>
                <Button
                  v-if="booking.queueTicket"
                  type="link"
                  size="small"
                  @click="viewQueueStatus(booking)"
                >
                  查看排队状态
                </Button>
                <Button
                  type="link"
                  size="small"
                  @click="viewBookingDetail(booking)"
                >
                  查看详情
                </Button>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div v-if="total > 0" class="pagination-wrapper">
          <Pagination
            v-model:current="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :show-size-changer="true"
            :show-quick-jumper="true"
            :show-total="
              (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
            "
            @change="handlePageChange"
            @show-size-change="handlePageSizeChange"
          />
        </div>
      </div>
    </Page>
  </div>
</template>

<style scoped>
.my-bookings-page {
  padding: 20px;
}

.bookings-container {
  max-width: 1200px;
  margin: 0 auto;
}

.filters-section {
  padding: 20px;
  margin-bottom: 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.bookings-list {
  margin-bottom: 24px;
}

.loading-state,
.empty-state {
  padding: 80px 20px;
  color: #6b7280;
  text-align: center;
}

.empty-icon {
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-state h3 {
  margin: 0 0 8px;
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
}

.empty-state p {
  margin: 0 0 24px;
  font-size: 16px;
}

.bookings-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.booking-card {
  padding: 20px;
  background: white;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
  transition: all 0.3s ease;
}

.booking-card:hover {
  box-shadow: 0 4px 16px rgb(0 0 0 / 15%);
  transform: translateY(-2px);
}

.booking-card.status-pending {
  border-left: 4px solid #f59e0b;
}

.booking-card.status-confirmed {
  border-left: 4px solid #3b82f6;
}

.booking-card.status-in-progress {
  border-left: 4px solid #10b981;
}

.booking-card.status-completed {
  border-left: 4px solid #6b7280;
}

.booking-card.status-cancelled {
  border-left: 4px solid #ef4444;
}

.booking-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 16px;
}

.service-name {
  margin: 0 0 4px;
  font-size: 18px;
  font-weight: 600;
  color: #1f2937;
}

.booking-time {
  margin: 0;
  font-size: 14px;
  color: #6b7280;
}

.booking-details {
  margin-bottom: 16px;
}

.detail-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.detail-row:last-child {
  margin-bottom: 0;
}

.detail-row .label {
  font-size: 14px;
  color: #6b7280;
}

.detail-row .value {
  font-size: 14px;
  font-weight: 500;
  color: #1f2937;
}

.detail-row .value.queue-number {
  font-weight: 600;
  color: #3b82f6;
}

.detail-row .value.remarks {
  font-style: italic;
  color: #6b7280;
}

.booking-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  padding-top: 16px;
  border-top: 1px solid #f3f4f6;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}
</style>
